#!/usr/bin/env bash

# Simple script to handle a DIY shutdown menu
# Requirements:
# - rofi
# - systemd or elogind (but you can replace the commands for anything)
# - If you don't have systemd or elogind, setup passwordless reboots
# and shutdowns:
#   # Linux:
# 	sudo EDITOR=nano visudo -f /etc/sudoers.d/55-nopasswd-power
#   # FreeBSD:
# 	sudo EDITOR=nano visudo -f /usr/local/etc/sudoers.d/55-nopasswd-power
# then enter:
# 	%wheel ALL=NOPASSWD:/sbin/reboot
# 	%wheel ALL=NOPASSWD:/sbin/shutdown
# 	%wheel ALL=NOPASSWD:/sbin/poweroff

# Info about some systemd states are available here:
#   https://www.freedesktop.org/software/systemd/man/systemd-sleep.conf.html#Description

# Options common in all situations. The very basics.
options="[Cancel]\nLogout\nShutdown\nReboot"

# Determines if running on systemd or loginctl
if [ -x "$(command -v systemctl)" ]; then
	hassystemd=true
elif [ -x "$(command -v loginctl)" ]; then
	haselogind=true
fi

# Determines if run from CLI with parameters.
if [ ! -z "$1" ]; then
	clirun=true
fi

if [ "$clirun" = true ]; then
	if [ "$1" = "--logout" ]; then
		chosen="Logout"
	elif [ "$1" = "--shutdown" ]; then
		chosen="Shutdown"
	elif [ "$1" = "--reboot" ]; then
		chosen="Reboot"
	elif [ "$1" = "--suspend" ]; then
		chosen="Suspend"
	elif [ "$1" = "--hibernate" ]; then
		chosen="Hibernate"
	elif [ "$1" = "--hybrid-sleep" ]; then
		chosen="Hybrid-sleep"
	elif [ "$1" = "--suspend-then-hibernate" ]; then
		chosen="Suspend-then-hibernate"
	fi
elif [ "$hassystemd" = true ] || [ "$haselogind" = true ]; then
	chosen=$(echo -e "$options\nSuspend\nHibernate\nHybrid-sleep\nSuspend-then-hibernate" | rofi -dmenu -i)
else
	chosen=$(echo -e "$options" | rofi -dmenu -i)
fi

if [ "$chosen" = "Logout" ]; then
	openbox --exit
elif [ "$chosen" = "Shutdown" ]; then
	if [ "$hassystemd" = true ]; then
		systemctl poweroff
	elif [ "$haselogind" = true ]; then
		loginctl poweroff
	else
		sudo shutdown || sudo poweroff
	fi
elif [ "$chosen" = "Reboot" ]; then
	if [ "$hassystemd" = true ]; then
		systemctl reboot
	elif [ "$haselogind" = true ]; then
		loginctl reboot
	else
		sudo reboot
	fi
elif [ "$chosen" = "Suspend" ]; then
	if [ "$hassystemd" = true ]; then
		systemctl suspend
	elif [ "$haselogind" = true ]; then
		loginctl suspend
	fi
	{{@@ lock_command @@}}
elif [ "$chosen" = "Hibernate" ]; then
	if [ "$hassystemd" = true ]; then
		systemctl hibernate
	elif [ "$haselogind" = true ]; then
		loginctl hibernate
	fi
	{{@@ lock_command @@}}
elif [ "$chosen" = "Hybrid-sleep" ]; then
	if [ "$hassystemd" = true ]; then
		systemctl hybrid-sleep
	elif [ "$haselogind" = true ]; then
		loginctl hybrid-sleep
	fi
	{{@@ lock_command @@}}
elif [ "$chosen" = "Suspend-then-hibernate" ]; then
	if [ "$hassystemd" = true ]; then
		systemctl suspend-then-hibernate
	elif [ "$haselogind" = true ]; then
		loginctl suspend-then-hibernate
	fi
	{{@@ lock_command @@}}
fi
